import React, { Component } from "react"
import { Descriptions, Tooltip, InputNumber, Modal, Switch } from 'antd';
import { QuestionCircleOutlined, EditOutlined } from "@ant-design/icons";
import TheButton from '@/components/TheButton';
import TheSwitch from '@/components/TheSwitch';
import { rechargeWithdrawList, rechargeWithdrawEdit } from '@/request/wallet/rechargeWithdraw'
import EditInput from "./editInput";

// 入口文案label
let entryCopyLabel = (<div>
  <text style={{ marginRight: 10 }}>入口维护文案</text>
  {/* <Tooltip placement="top" title={() => { return '入口关闭时展示维护文案' }}  >
    <QuestionCircleOutlined style={{ fontSize: '16px' }} />
  </Tooltip> */}
</div>)
// 入口开关label
let entrySwitchLabel = (<div>
  <text style={{ marginRight: 10 }}>入口开关</text>
  {/* <Tooltip placement="top" title={() => { return '关闭时,APP点击充值会展示维护文案' }}  > */}
  {/* <QuestionCircleOutlined style={{ fontSize: '16px' }} /> */}
  {/* </Tooltip> */}
</div>)
export default class Recharge extends Component {
  constructor() {
    super()
    this.state = {
      hourlyQuota: "",
      moneyLimit: '',//触发验证的最大金额额度
      dailyCollectionAmount: "",
      imAmountConfigId: '',//业务id
      obj: {},
      limitationType: '', //其他充值配置参数
      otherCount: '', //其他次数
      otherMinute: '', //其他时间
      isOtherEdit: false,// 是否点击其他充值时的编辑，
      oldValue: '',//旧数据输入框
      switchLoading: false,//开关
      warning: false,
      otherMinuteWarning: false,//是否填写值修改颜色
      otherCountWarning: false,//是否填写值修改颜色
      otherMinuteOldValue: '',//其他配置项输入的值
      otherCountOldValue: '',//其他配置项输入的值
      editType: '',//提现充值类型
    }
  }
  componentDidMount() {
    this.getData()
  }
  // 获取数据
  getData = async () => {
    let res = await rechargeWithdrawList({ type: 4 })
    if (res.code === 0 && res.data) {
      let data = res.data
      this.setState({
        moneyLimit: {
          label: '触发验证的最大金额额度',
          key: 'hourlyQuota',
          value: data.hourlyQuota/100,
          minValue: 1,
          maxValue: 800000,
          status: 0, //编辑 0 保存1
        },
      })
      let limitationType = data.limitationType.split('-') // 其他充值配置项
      this.setState({
        obj: {
          // minimumAmount: {
          //   label: '单次充值最低金额',
          //   key: 'minimumAmount',
          //   value: (data.minimumAmount / 100).toFixed(2),
          //   minValue: 0.01,
          //   maxValue: 999999.99,
          //   precision: 2,
          //   status: 0, //编辑 0 保存1
          //   bgColor: false
          // },
          // maximumAmount: {
          //   label: '单次充值最大金额',
          //   key: 'maximumAmount',
          //   value: (data.maximumAmount / 100).toFixed(2),
          //   minValue: 0.01,
          //   maxValue: 999999.99,
          //   precision: 2,
          //   status: 0, //编辑 0 保存1
          //   bgColor: false
          // },
          // dayAmount: {
          //   label: '单日充值总额度',
          //   key: 'dayAmount',
          //   value: (data.dayAmount / 100).toFixed(2),
          //   minValue: 0.01,
          //   maxValue: 999999.99,
          //   precision: 2,
          //   status: 0, //编辑 0 保存1
          //   bgColor: false
          // },
          // dayNumber: {
          //   label: '单日充值最大次数',
          //   key: 'dayNumber',
          //   value: data.dayNumber,
          //   minValue: 1,
          //   maxValue: 10000,
          //   precision: 0,
          //   status: 0, //编辑 0 保存1
          //   bgColor: false
          // },
          timeout: {
            label: '超时未支付时间（秒）',
            key: 'timeout',
            value: data.timeout,
            minValue: 1,
            maxValue: 600,
            precision: 0,
            status: 0, //编辑 0 保存1
            bgColor: false
          },
          minutesNumber: {
            label: '1分钟内充值最大次数',
            key: 'minutesNumber',
            value: data.minutesNumber,
            minValue: 1,
            maxValue: 999,
            precision: 0,
            status: 0, //编辑 0 保存1
            bgColor: false
          },
          hourNumber: {
            label: '1天内充值最大次数',
            key: 'hourNumber',
            value: data.hourNumber,
            minValue: 1,
            maxValue: 999,
            precision: 0,
            status: 0, //编辑 0 保存1
            bgColor: false
          },
          // text: {
          //   label: entryCopyLabel,
          //   key: 'text',
          //   value: data.text,
          //   status: 0, //编辑 0 保存1
          //   bgColor: false,
          //   precision: 0,
          // },
          entrySwitch: {
            label: entrySwitchLabel,
            key: 'entrySwitch',
            value: data.entrySwitch === 0 ? true : false,
            status: 0, //编辑 0 保存1
          },
          realnameOrNot: {
            label: '是否需要实名',
            key: 'realnameOrNot',
            value: data.realnameOrNot === 0 ? true : false,
            status: 0, //编辑 0 保存1
          },
        },
        //data.hourlyQuota
        // moneyLimit: {
        //   label: '触发验证的最大金额额度',
        //   key: 'moneyLimit',
        //   value: 9,
        //   minValue: 0.01,
        //   maxValue: 999999.99,
        //   precision: 2,
        //   status: 0, //编辑 0 保存1
        // },
        hourlyQuota: data.hourlyQuota,
        hourlyQuotaUpdateTime:data.hourlyQuotaUpdateTime,
        dailyCollectionAmount: data.dailyCollectionAmount / 100,
        otherCount: limitationType[1],
        otherMinute: limitationType[0],
        imAmountConfigId: data.imAmountConfigId,
        otherCountOldValue: limitationType[1],
        otherMinuteOldValue: limitationType[0],
        editType: 1
      })
    }
  };
  // 编辑 
  edit = (data) => {
    let { obj, otherMinuteOldValue, otherCountOldValue, oldValue } = this.state
    Object.values(obj).map((v, i) => {
      if (data.index === i) {
        console.log();
        oldValue = v.value
        return v.status = 1
      } else {
        this.state.isOtherEdit = false
        return v.status = 0
      }
    })
    console.log("obj",obj);
    console.log("oldValue",oldValue);
    this.setState({
      obj,
      oldValue,
      warning: false,
      otherCount: otherCountOldValue,
      otherMinute: otherMinuteOldValue
    })
  }
  // 取消
  cancel = (data) => {
    let { obj } = this.state
    Object.values(obj).map((v, i) => {
      if (data.index === i) {
        v.status = 0
        return v
      }

    })
    this.setState({
      obj,
      warning: false
    })
  }
  // 保存时掉接口
  saveFn = async (params, v) => {
    console.log("v:",v);
    let res = await rechargeWithdrawEdit({
      imAmountConfigId: this.state.imAmountConfigId, [v.key]: v.precision === 0 ? params.data.value : React.$transNum(params.data.value, 0, 2)
    })
    if (res.code === 0) { 
      v.status = 0
      v.value = params.data.value
      React.$message({ type: 'success', content: '保存成功' })
      this.getData()
      return v
    }
  }
  // 保存
  save = (params) => {
    let { obj } = this.state
    let numValues = Number(params.data.value)
    Object.values(obj).map(async (v, i) => {
      if (params.index === i) {
        if (params.data.key === 'minimumAmount' && numValues >= Number(obj.maximumAmount.value)) {
          Modal.error({
            content: '单次最低金额不能大于或等于单次最高金额',
            okText: '确定'
          });
          return false
        }
        if (params.data.key === 'maximumAmount') {
          if (numValues <= Number(obj.minimumAmount.value)) {
            Modal.error({
              content: '单次最高金额不能小于或等于单次最低金额',
              okText: '确定'
            });
          } else if (numValues > Number(obj.dayAmount.value)) {
            Modal.error({
              content: '单次充值最高金额不能大于单日充值总额度',
              okText: '确定'
            });
          } else {
            this.saveFn(params, v)
          }
          return false
        }
        if (params.data.key === 'dayAmount' && numValues < Number(obj.maximumAmount.value)) {
          Modal.error({
            content: '单日充值总额度不能小于单次充值最高金额',
            okText: '确定'
          });
          return false
        }
        this.saveFn(params, v)
      }
    })
  }
  // 开关设置
  switchChange = (e, params, index) => {
    let { obj } = this.state
    let entrySwitchContent = params.value ? '关闭后，用户将不能进入充值页' : '开启后，用户可进入充值页'
    let realnameOrNotContent = params.value ? '关闭后，用户充值无需实名认证' : '开启后，用户充值需实名认证'
    Object.values(obj).map(async (v, i) => {
      let _this = this
      if (index === i) {
        Modal.confirm({
          title: '提示',
          content: v.key === 'entrySwitch' ? entrySwitchContent : realnameOrNotContent,
          okText: '确认',
          cancelText: '取消',
          async onOk() {
            let res = await rechargeWithdrawEdit({
              imAmountConfigId: _this.state.imAmountConfigId, [v.key]: e ? 0 : 1
            })
            if (res.code === 0) {
              React.$message({ type: 'success', content: v.value ? '关闭成功' : '开启成功' })
              _this.getData()
            }
          },
        });
        this.setState({ obj })
      }
    })
  }
  //其他充值配置编辑
  editOtherRecharge = () => {
    let { obj, otherMinuteOldValue, otherCountOldValue, oldValue } = this.state
    Object.values(obj).map((v) => {
      oldValue = v.value
      return v.status = 0
    })
    this.setState({
      isOtherEdit: true,
      oldValue,
      otherCount: otherCountOldValue,
      otherMinute: otherMinuteOldValue
    })
  }
  // 取消编辑其他配置 
  cancelOtherRecharge = () => {
    let { otherMinuteOldValue, otherCountOldValue } = this.state
    this.setState({
      isOtherEdit: false,
      otherCount: otherCountOldValue,
      otherMinute: otherMinuteOldValue
    })

  }
  // 保存编辑其他配置 
  saveOtherRecharge = async () => {
    let { otherCount, otherMinute, imAmountConfigId } = this.state
    let regex = /^(?!.*(?<![\d.])0\d).*$/ //不能以.结尾 并且除小数点外不能连续输入0
    if (!regex.test(otherMinute) || !regex.test(otherCount)) {
      React.$message({ type: 'error', content: '输入格式不正确!' })
      return false
    }
    if (otherMinute === '' && otherCount === '') {
      this.setState({ otherMinuteWarning: true, otherCountWarning: true })
      React.$message({ type: 'error', content: '此项为必填项！' })
      return false
    }
    if (otherMinute === '') {
      this.setState({ otherMinuteWarning: true })
      React.$message({ type: 'error', content: '此项为必填项！' })
      return false
    }
    if (otherCount === '') {
      this.setState({ otherCountWarning: true })
      React.$message({ type: 'error', content: '此项为必填项！' })
      return false
    }
    if (otherMinute < 1 || otherMinute > 60) {
      React.$message({ type: 'error', content: '只能输入1-60的数字' })
      return false
    }
    if (otherCount < 1 || otherCount > 1000) {
      React.$message({ type: 'error', content: '只能输入1-1000的数字' })
      return false
    }
    let params = {
      imAmountConfigId: imAmountConfigId,
      limitationType: otherMinute + '-' + otherCount
    }

    let res = await rechargeWithdrawEdit({
      ...params
    })
    if (res.code === 0) {
      React.$message({ type: 'success', content: '保存成功' })
      this.getData()
      this.setState({
        isOtherEdit: false,
      })
    }
  }
  //其他配置中次数值改变
  otherCountChange = (e) => {
    let value = e.target.value
    if (value !== '') {
      this.setState({
        otherCountWarning: false
      })
    }
    value = value.replace(/[^\d]/g, '')// 只能是数字
    this.setState({
      otherCount: value,
    })
  }
  //其他配置中时间值改变
  otherMinuteChange = (e) => {
    let value = e.target.value
    if (value !== '') {
      this.setState({
        otherMinuteWarning: false
      })
    }
    value = value.replace(/[^\d]/g, '')// 只能是数字
    this.setState({
      otherMinute: value,
    })
  }
  //编辑触发验证的最大金额额度
  editMoneyLimit = () => {
    let { moneyLimit, obj } = this.state
    moneyLimit.status = 1
    let otherOldValue = ''
    Object.values(obj).map((v) => {
      otherOldValue = v.value
      v.status = 0
      return v
    })
    this.setState({
      obj,
      otherOldValue,
      moneyLimit
    })
  }
  //保存触发验证的最大金额额度
  saveMoneyLimit = async (params) => {
    let { moneyLimit, imAmountConfigId,hourlyQuotaUpdateTime } = this.state
    let res = await rechargeWithdrawEdit({ imAmountConfigId: imAmountConfigId, hourlyQuota: params.data.value * 100,hourlyQuotaUpdateTime})
    if (res.code === 0) {
      this.setState({
        moneyLimit: {
          ...moneyLimit,
          value: params.data.value,
          status: 0
        }
      })
      React.$message({ type: 'success', content: '保存成功' })
      this.getData()
    }
  }
  clean = async () => {
    React.$confirm({
      title: "提示",
      type: 'warning',
      content: "是否清空累积存续额度？",
      onOk: async () => {
        let { imAmountConfigId } = this.state
        let res = await rechargeWithdrawEdit({ imAmountConfigId: imAmountConfigId, dailyCollectionAmount: 0 })
        if (res.code === 0) {
          React.$message({ type: 'success', content: '清空成功' })
          this.getData()
        }
      }
    });

  }

  //取消触发验证的最大金额额度
  cancelMoneyLimit = () => {
    let { moneyLimit } = this.state
    moneyLimit.status = 0
    this.setState({
      moneyLimit
    })
  }
  render() {
    const { moneyLimit, obj, otherMinute, otherCount, isOtherEdit, switchLoading, otherMinuteWarning, otherCountWarning, editType, dailyCollectionAmount, hourlyQuota } = this.state
    let style = { display: 'flex', justifyContent: 'center', alignItems: 'center' }
    return (
      <div >
        <div style={{ fontWeight: 'bold', marginBottom: 20, fontSize: 16 }}>充值配置</div>
        <Descriptions layout="vertical" bordered column={10} size='small' labelStyle={style} style={{ width: 1650 }}>
          {
            Object.values(obj).map((item, index) => {
              return (
                <Descriptions.Item label={item.label} style={{ textAlign: (item.key === 'realnameOrNot' || item.key === 'entrySwitch') && 'center' }}>
                  {
                    item.key === 'realnameOrNot' || item.key === 'entrySwitch' ?
                      <TheSwitch haspermi={["myPocket:precharge:switch"]} checked={item.value} onChange={(e) => this.switchChange(e, item, index)} loading={switchLoading} />
                      : <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
                        <EditInput editType={editType} editData={item} editIdex={index} onEdit={this.edit} onSave={this.save} onCancel={this.cancel} />
                      </div>
                  }
                </Descriptions.Item>
              )
            })
          }
        </Descriptions>
        <div style={{ margin: '20px 0', fontWeight: 'bold' }}>充值收款额度</div>
        <div className="phoneCode">
          <span>  在当日7:00:00-次日6:59:59期间，每小时分配额度：</span>
          <EditInput editData={moneyLimit} onEdit={this.editMoneyLimit} onSave={this.saveMoneyLimit} onCancel={this.cancelMoneyLimit} />
        </div>
        <div>
          7:00:00-现在，存续额度：{dailyCollectionAmount}
          <TheButton haspermi={["myPocket:precharge:edit"]} onClick={this.clean}>清空</TheButton>
        </div>
      </div >
    )
  }
}